package com.buffered.exam;

import java.io.*;

/**
 * @author げっしょく
 * @date 2021/8/1
 */
public class Demo5Amend {
    static byte[] bytes = new byte[1024];
    static int len = 0;

    public static void main(String[] args) throws IOException {
        File f = new File("D:\\itheima\\资料\\JavaSE\\JavaSE每日作业");
//        FileInputStream fis = new FileInputStream("D:\\Git");
        File f2 = new File("C:\\");
        copeFile(f, f2);
    }

    /**
     * 拷贝文件夹
     * @param f   拷贝源
     * @param f2  目的地
     */

    private static void copeFile(File f, File f2) {
        //获取当前文件夹的所有文件和文件夹
        File[] files = f.listFiles();
        //判断数组是否为空
        if (files != null) {
            //遍历文件夹里面的文件和文件夹
            for (File file : files) {
                //判断是否是文件
                if (!file.isFile()) {
                    //是文件就通过调用
                    File f1 = new File(TempFile(file.getAbsolutePath(), f2));
                    copeFile(file, f2);
                } else {
                    FileInputStream fis = null;
                    FileOutputStream fos = null;
                    try {
                        fis = new FileInputStream(file.getAbsolutePath());
                        fos = new FileOutputStream(TempFile(file.getAbsolutePath() , f2));
                        while ((len = fis.read(bytes)) != -1) {
                            fos.write(bytes);
                        }
                        fos.flush();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

    public static String TempFile(String tempString , File f2) {
        return  (f2.getAbsolutePath().endsWith("\\") ? f2.getAbsolutePath() : f2.getAbsolutePath() + "\\") +tempString.substring(3);
    }

}
